import pandas as pd
from sklearn.cluster import KMeans
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import seaborn as sns
import joblib

# 读取源数据
df = pd.read_csv("new_file_with_scores_kmeans.csv")

# 定义特征列
features = ['Q10', 'Q12', 'Q13', 'Q14']

# 加载之前保存的聚类结果
best_clusters = joblib.load('best_clusters.pkl')
# 加载之前保存的随机种子值
with open('best_seed.txt', 'r') as file:
    best_seed = int(file.read())

# 使用之前保存的随机种子值初始化 KMeans 对象
kmeans = KMeans(n_clusters=4, random_state=best_seed)
kmeans.fit(df[features])

# 获取聚类标签
labels = kmeans.labels_

# 使用t-SNE进行降维
tsne = TSNE(n_components=2, random_state=best_seed)
tsne_data = tsne.fit_transform(df[features])

# 将降维后的数据和聚类标签合并为DataFrame
tsne_df = pd.DataFrame(tsne_data, columns=['Dimension 1', 'Dimension 2'])
tsne_df['Cluster'] = labels.astype(str)

# 绘制 t-SNE 散点图，使用更鲜明的颜色来表示不同的聚类
plt.figure(figsize=(8, 6))
sns.scatterplot(data=tsne_df, x='Dimension 1', y='Dimension 2', hue='Cluster', palette='bright')
plt.title('t-SNE Visualization of Clusters')
plt.show()
